﻿using AutoMapper;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Write.Application.Common.Menu;
using MediatR;

namespace B.S.BasicData.Write.Application.Handler.Menu
{
    public class DelMenuCommandHandle:IRequestHandler<DelMenuCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<MenuModel> MeunDal;
        private readonly IMapper mapper;
        public DelMenuCommandHandle(IBaseRepository<MenuModel> meunDal, IMapper mapper)
        {
            MeunDal = meunDal;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(DelMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var result = MeunDal.GetAll().ToList();
            var count = await Del(request.MenuId, result);

            if (count > 0)
            {
                res.Code = ApiEnum.Success;
                res.Message = "删除成功";
                return await Task.FromResult(res);
            }
            else
            {
                res.Code = ApiEnum.Error;
                res.Message = "删除失败";
                return await Task.FromResult(res);
            }
        }

        private async Task<int> Del(int menuId, List<MenuModel> result)
        {
            int count = 0;
            var res1 = result.FirstOrDefault(x => x.MenuId == menuId);
            if (res1 != null && res1.IsDeleted == false)
            {
                res1.IsDeleted = true;
                await MeunDal.Update(res1);
                count++;

                var res = result.Where(x => x.ParentId == menuId && x.IsDeleted == false).ToList();
                //有子集
                foreach (var item in res)
                {
                    count += await Del(item.MenuId, result);
                }

            }
            return count;
        }


    }
}
